package com.hdl.school.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.util.Log;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;

/**
 * Created by Admin on 2017/3/20.
 */

public class BitmapUtil {
    public static String convertIconToString(String path){
        try
        {
            File file = new File(path);
            if(file.exists())
            {
                Bitmap bitmap = BitmapFactory.decodeFile(path);
                if(bitmap==null){
                    return null;
                }
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 60, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
                byte[] appicon = baos.toByteArray();// 转为byte数组
                return Base64.encodeToString(appicon, Base64.DEFAULT);
            }else{
                return "";
            }
        } catch (Exception e)
        {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }


    /**
     * string转成bitmap
     *
     * @param st
     */
    public static Bitmap convertStringToIcon(String st)
    {
       // OutputStream out;
        Bitmap bitmap = null;
        try
        {
            // out = new FileOutputStream("/sdcard/aa.jpg");
            byte[] bitmapArray;
            bitmapArray = Base64.decode(st, Base64.DEFAULT);
            bitmap =
                    BitmapFactory.decodeByteArray(bitmapArray, 0,
                            bitmapArray.length);
            // bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            return bitmap;
        }
        catch (Exception e)
        {
            return null;
        }
    }
}
